package com.sanji.sjmallutils;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmodule.phoneshell.ShellWebViewActivity;
import com.sanji.sjmallwidget.BottomPopWindow;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * Created by fhm on 2016/12/13.
 */
public class ImageUtil {
    public static SharePreferenceUtil spUtil;

    public static void getScreenSize(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        int height = windowManager.getDefaultDisplay().getHeight();
        if (spUtil == null) {
            spUtil = new SharePreferenceUtil(context);
        }
        spUtil.put(ConfigConts.ScreenWidth, width);
        spUtil.put(ConfigConts.ScreenHight, height);
    }

    /**
     * @param context
     * @return 图片的宽是屏幕宽的三分之一
     */
    public static int setImageWidth(Context context, int i) {
        if (spUtil == null) {
            getScreenSize(context);
        }
        int imageWidth = spUtil.getInt(ConfigConts.ScreenWidth, 0);
        return imageWidth / i;
    }

    /**
     * @param
     * @return 根据图片的高是图片的宽的2/3
     */
    public static int setImageHight(int width) {
        return (width * 2) / 3;
    }

    /**
     * @param
     * @return 根据图片的宽和高一致
     */
    public static int setImageHightSampleWidth(int width) {
        return width;
    }


    //----------------拍照、相册相关
    // 拍照后的原图
    private String temp_pic;
    // 裁剪后的图片
    private String crop_pic = "crop_img.jpg";
    // 压缩后的图片
    private String zoom_pic = "zoom_img";

    // private Bitmap image = null;

    private int imgSize;

    private int width = 0, height = 0;

    private Activity mActivity = null;

    private File dirFile = null;

    private BottomPopWindow bomPop = null;
    private TextView cameraBtn = null, albumBtn = null, cancelBtn = null;

    private Handler mHandler;

    public ImageUtil(Activity activity,Handler handler){
        this.mActivity = activity;
        this.mHandler = handler;
        dirFile = new File(SDCardUtil.getImgTemp());
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        initPop();
    }

    public ImageUtil(Activity activity,int imgWidth,int imgHeight,int imgSize){

        this.mActivity = activity;
        this.width = imgWidth;
        this.height = imgHeight;
        this.imgSize = imgSize;

        dirFile = new File(SDCardUtil.getImgTemp());
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        initPop();
    }

    private void initPop() {
        RelativeLayout view = (RelativeLayout) LayoutInflater.from(mActivity)
                .inflate(R.layout.dialog_camera_alert, null);
        bomPop = new BottomPopWindow(mActivity, view);

        cameraBtn = (TextView) view.findViewById(R.id.dialog_camera_tv);
        cameraBtn.setOnClickListener(cameraListener);
        albumBtn = (TextView) view.findViewById(R.id.dialog_photo_tv);
        albumBtn.setOnClickListener(albumListener);
        cancelBtn = (TextView) view.findViewById(R.id.dialog_camera_cancel);
        cancelBtn.setOnClickListener(cancelListener);
    }

    public void showDialog(View v) {
        if (bomPop != null) {
            bomPop.show(v);
        }
    }

    public void dismissDialog() {
        if (bomPop != null) {
            bomPop.dismiss();
        }
    }

    // 相机
    View.OnClickListener cameraListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // BitmapUtils.cameraMethod(myActy);
            cameraMethod();
            dismissDialog();
        }
    };
    // 相册
    View.OnClickListener albumListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // BitmapUtils.galleryMethod(myActy);
            galleryMethod();
            dismissDialog();
        }
    };
    // 取消
    View.OnClickListener cancelListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (bomPop != null) {
                bomPop.dismiss();
            }

            mHandler.sendEmptyMessage(ConfigConts.PHOTO_REQUEST_CANCEL);

        }
    };

    /**
     * 相机拍照
     *
     */
    public void cameraMethod() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        if (dirFile.exists()) {
            temp_pic = Tools.getCurrentTime() + ".jpg";
            File file = new File(dirFile, temp_pic);
            if (file.exists()){
                file.delete();
            }
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
//            intent.putExtra(MediaStore.EXTRA_OUTPUT,
//                    FileProvider.getUriForFile(mActivity.getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider",file));
            Uri uri = getOutputMediaFileUri(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
        }
        mActivity.startActivityForResult(intent,
                ConfigConts.PHOTO_REQUEST_TAKEPHOTO);

    }

    private Uri getUriForFile(File file){
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            uri = FileProvider.getUriForFile(mActivity.getApplicationContext(),"com.sanji.sjmallapp.fileprovider",file);
        }else{
            uri = Uri.fromFile(file);
        }
        return uri;
    }

    private Uri getOutputMediaFileUri(File file){
        return getUriForFile(file);
    }

    /**
     * 获取相机图片
     * @return
     */
    public File getCameraPath(){
        File file = new File(dirFile, temp_pic);
        if (file.exists()){
            return file;
        }else{
            return null;
        }
    }

    /**
     * 相册
     *
     */
    public void galleryMethod() {
        Intent picture = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        mActivity.startActivityForResult(picture,
                ConfigConts.PHOTO_REQUEST_GALLERY);
    }

    /**
     * 拍照图片裁剪
     *
     */
    public void cropCameraMethod(Context context) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
//        intent.setDataAndType(Uri.fromFile(new File(dirFile, temp_pic)),
//                "image/*");
        intent.setDataAndType(getImageContentUri(context,new File(dirFile, temp_pic)),
                "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
//		intent.putExtra("crop", "true");
        intent.putExtra("scale", "true");
        intent.putExtra("scaleUpIfNeeded", true);

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", width);
        intent.putExtra("aspectY", height);

        // outputX,outputY 是剪裁图片的宽高
//		intent.putExtra("outputX", width);
//		intent.putExtra("outputY", height);

        intent.putExtra("output", Uri.fromFile(new File(dirFile, crop_pic)));
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);
        // intent.putExtra("return-data", true);
        // intent.putExtra("noFaceDetection", true);
        mActivity.startActivityForResult(intent, ConfigConts.PHOTO_REQUEST_CUT);
    }

    /**
     * 7.0系统对应使用Content Uri ，之下的使用File Uri
     * @param imageFile
     * @return
     */
    private Uri getImageContentUri(Context context,File imageFile){
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);
        if (cursor!=null && cursor.moveToFirst()){
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri,""+id);
        }else{
            if (imageFile.exists()){
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            }else{
                return null;
            }
        }

    }

    /**
     * 相册图片裁剪
     *
     * @param uri
     */
    public void cropGalleryMethod(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
//		intent.putExtra("crop", "true");
        intent.putExtra("scale", "true");
        intent.putExtra("scaleUpIfNeeded", true);
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", width);
        intent.putExtra("aspectY", height);

        // outputX,outputY 是剪裁图片的宽高
//		intent.putExtra("outputX", width);
//		intent.putExtra("outputY", height);

        intent.putExtra("output", Uri.fromFile(new File(dirFile, crop_pic)));
        intent.putExtra("outputFormat", "JPEG");
        // intent.putExtra("return-data", true);
        // intent.putExtra("noFaceDetection", true);
        mActivity.startActivityForResult(intent, ConfigConts.PHOTO_REQUEST_CUT);
    }

    public File getCropPath(){
        File file = new File(dirFile, crop_pic);
        if (file.exists()) {
            return file;
        }else{
            return null;
        }
    }

    // 图片按比例大小压缩方法（根据路径获取图片并压缩）--
    public String getImage(Object index) {

        File file = new File(dirFile, crop_pic);
        if (file.exists()) {
//			long fileLenght = file.length();
//			if (fileLenght < imgSize * 1024) {
//				return file.getPath();
//			}
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
            newOpts.inJustDecodeBounds = true;
            Bitmap image = BitmapFactory.decodeFile(file.getPath(), newOpts);// 此时返回bm为空
            newOpts.inJustDecodeBounds = false;
            int w = newOpts.outWidth;
            int h = newOpts.outHeight;
            // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
            // float hh = 800f;//这里设置高度为800f
            // float ww = 480f;//这里设置宽度为480f
            // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
            int be = 1;// be=1表示不缩放
            if (w >= h && w > width) {// 如果宽度大的话根据宽度固定大小缩放
                be = (int) (newOpts.outWidth / width);
            } else if (w < h && h > height) {// 如果高度高的话根据宽度固定大小缩放
                be = (int) (newOpts.outHeight / height);
            }
            if (be <= 0)
                be = 1;
            newOpts.inSampleSize = be;// 设置缩放比例
            // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了

            image = BitmapFactory.decodeFile(file.getPath(), newOpts);
            return compressImage(image,index);// 压缩好比例大小后再进行质量压缩
        }else{
            return "";
        }

    }

    // 质量压缩
    private String compressImage(Bitmap image,Object index) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (options > 10 && baos.toByteArray().length / 1024 > imgSize) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            if (options > 10) {
                options -=10;// 每次都减少10
            }
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        image = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        File myCaptureFile = null;
        if (image != null) {
            try {
                String imgName = zoom_pic + index + ".jpg";
                myCaptureFile = new File(dirFile, imgName);
                BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream(myCaptureFile));
                image.compress(Bitmap.CompressFormat.JPEG, 85, bos);
                bos.flush();
                bos.close();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                image.recycle();
            }

        }

        return myCaptureFile.getPath();
    }
}
